/*
 * @Description:  职员信息
 * @Author: kanglin
 * @Date: 2018-05-24 09:14:19
 * @Copyright: Created by Panxsoft.
 */

// import axios from 'axios';
import { Message } from 'iview';
import API_LIST from 'src/API_LIST';
import axios from 'src/utils/axios-interceptors';
import { $t } from 'src/i18n';

const USER_TYPE = {
	PANX: 'panx',
	STORE: 'store',
	CUSTOMER: 'customer',
};

/**
 * 通过用户类型得到 staff url
 * @param {string} user_type
 */
function resolveStaffUrl(user_type) {
	let staff_url = '';
	switch (user_type) {
	case USER_TYPE.PANX:
		staff_url = API_LIST.STAFF;
		break;
	case USER_TYPE.CUSTOMER:
		staff_url = API_LIST.CUST_STAFF;
		break;
	case USER_TYPE.STORE:
		staff_url = API_LIST.STORE_STAFF;
		break;
	default:
		break;
	}
	return staff_url;
}

/* eslint-disable no-shadow, no-param-reassign */
const state = {
	staff_role_index: [],
};

const getters = {
	getStaffRoleIndex(state) {
		return state.staff_role_index;
	},
};

const actions = {

	/**
     * 获取职员的分类
     * @param {*} context
     */
	fetchInitailStaffDataAction(context) {
		// context.commit('spinShow/showSpin', $t('common.loading'), { root: true });
		const user_type = context.rootGetters['userToken/getUserType'];
		const staff_url = resolveStaffUrl(user_type);
		axios.get(`${staff_url}/create`)
			.then(({ data }) => {
				if (parseInt(data.code, 10) !== 0) {
					throw new Error(data.error);
				}
				context.state.staff_role_index = data.roles;
			})
			.catch((err) => {
				Message.error(err.message || err.statusText);
			});
		// .finally(() => {
		// 	context.commit('spinShow/closeSpin', $t('common.loading'), { root: true });
		// });
	},

	/**
	 * 更新个人信息
	 * @param {object} context
	 * @param {object} param1
	 */
	updateStaffAction(context, { id, form }) {
		context.commit('spinShow/showSpin', $t('common.loading'), { root: true });
		const user_type = context.rootGetters['userToken/getUserType'];
		const staff_url = resolveStaffUrl(user_type);
		const body = { ...form, _method: 'PUT' };
		return axios.post(`${staff_url}/${id}`, body)
			.then(({ data }) => {
				if (parseInt(data.code, 10) !== 0) {
					throw new Error(data.error);
				}
				context.commit('userToken/updateUserInfo', form, { root: true });
				return data;
			})
			.catch((err) => {
				Message.error(err.message || err.statusText);
			})
			.finally(() => {
				context.commit('spinShow/closeSpin', $t('common.loading'), { root: true });
			});
	},


};

const mutations = {

};
/* eslint-enable no-shadow, no-param-reassign */

export default {
	state,
	getters,
	actions,
	mutations,
	namespaced: true,
};
